package org.railage.client.beans;

import java.util.Arrays;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

import org.apache.log4j.Logger;
import org.railage.common.protocol.Result;
import org.railage.server.services.StationService;

@ManagedBean(name = "editStations")
@ViewScoped
public class EditStationsBean {

	private static final Logger log = Logger.getLogger(EditStationsBean.class);
	
	private StationService stationService = new StationService();

	private List<String> stations = null;
	private String newStation;
	private String stationToDelete;
	
	public EditStationsBean() {
		updateStationsArr();
	}
	
	public void updateStationsArr() {
		stations = Arrays.asList(stationService.getStationNames(null));
	}

	public List<String> getStations() {
		return stations;
	}
	
	public void add() {
		Result result = stationService.addStation(newStation);
		updateStationsArr();
		
		log.debug("Add station: " + newStation + "; Result: " + result.getResult());

		FacesMessage message;
		if (result.isNoError()) {
			message = new FacesMessage(FacesMessage.SEVERITY_INFO, result.getResult(), "");
		} else {
			message = new FacesMessage(FacesMessage.SEVERITY_ERROR, result.getResult(), "");
		}
		FacesContext.getCurrentInstance().addMessage(null, message);
	}

	public String getNewStation() {
		return newStation;
	}

	public void setNewStation(String newStation) {
		this.newStation = newStation;
	}
	
	public String getStationToDelete() {
		return stationToDelete;
	}

	public void setStationToDelete(String stationToDelete) {
		this.stationToDelete = stationToDelete;
	}

	public void delete() {
		Result result = stationService.deleteStation(stationToDelete);
		updateStationsArr();
		
		log.debug("Delete station: " + stationToDelete + "; Result: " + result.getResult());
		
		FacesMessage message;
		if (result.isNoError()) {
			message = new FacesMessage(FacesMessage.SEVERITY_INFO, result.getResult(), "");
		} else {
			message = new FacesMessage(FacesMessage.SEVERITY_ERROR, result.getResult(), "");
		}
		FacesContext.getCurrentInstance().addMessage(null, message);
	}
	
}
